package cn.blue.pet.service.impl;

import cn.blue.base.config.BussinessException;
import cn.blue.base.util.*;
import cn.blue.org.domain.Employee;
import cn.blue.org.domain.Shop;
import cn.blue.org.mapper.EmployeeMapper;
import cn.blue.org.mapper.ShopMapper;
import cn.blue.pet.domain.OrderPetAcquisition;
import cn.blue.pet.domain.SearchMasterMsg;
import cn.blue.pet.domain.SearchMasterMsgAuditLog;
import cn.blue.pet.dto.AcceptDto;
import cn.blue.pet.mapper.OrderPetAcquisitionMapper;
import cn.blue.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.blue.pet.mapper.SearchMasterMsgMapper;
import cn.blue.pet.query.SearchMasterMsgQuery;
import cn.blue.pet.service.ISearchMasterMsgService;
import cn.blue.base.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hui
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;



    @Override
    public void search(SearchMasterMsg searchMasterMsg) {

        //保存数据到数据库
        super.add(searchMasterMsg);
        //参数校验非空
        if(StringUtils.isEmpty(searchMasterMsg.getAddress() )|| StringUtils.isEmpty(searchMasterMsg.getName())){

            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("未完整填写信息，请重新填写!");
            searchMasterMsgAuditLogMapper.add(log);

            throw new BussinessException("未完整填写信息，请重新填写!");

        }
        //百度ai审核
        StringBuffer sb = new StringBuffer();
        sb.append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getName())
                .append(searchMasterMsg.getTitle());
        if (!BaiduAuditUtils.TextCensor(sb.toString())){
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("填写信息不合规，请重新填写！");
            searchMasterMsgAuditLogMapper.add(log);
            throw new BussinessException("填写信息不合规，请重新填写");
        }
        searchMasterMsg.setState(1);

        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> all = shopMapper.findAll();
        //获取集合最近距离的店铺
        Shop shop = DistanceUtil.getNearestShop(point, all);
        if (shop!=null){
            searchMasterMsg.setShopId(shop.getId());
        }
        searchMasterMsgMapper.update(searchMasterMsg);





    }

    @Override
    public PageList<SearchMasterMsg> selectSearchByParam(SearchMasterMsgQuery searchMasterMsg) {
        Integer totals = searchMasterMsgMapper.selectSearchByParamCount(searchMasterMsg);
        if (totals==null||totals==0){
            return new PageList<>(0,new ArrayList<>());
        }
        List<SearchMasterMsg> searchMasterMsgsPageList = searchMasterMsgMapper.selectSearchByParamPage(searchMasterMsg);
        return new PageList<>(totals,searchMasterMsgsPageList);


    }

    @Override
    public void reject(Long id, Employee employee) {
        SearchMasterMsg msg = searchMasterMsgMapper.findById(id);
        if (msg == null) {
            throw new BussinessException("该消息不存在");
        }
        msg.setState(1);
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
        //添加拒单日志
    }

    @Override
    public void accept(AcceptDto dto) throws Exception {
        SearchMasterMsg msg = searchMasterMsgMapper.findById(dto.getMsgId());
        if (msg == null){
            throw new BussinessException("消息不能为空");
        }
        synchronized (msg.getId()){
            Employee employee = employeeMapper.findById(dto.getHandler());
            if (employee == null){
                throw new BussinessException("不存在该员工!");
            }
            if (msg.getState()==1 && msg.getShopId().equals(employee.getShopId())){
                msg.setState(2);
                searchMasterMsgMapper.update(msg);
            }
            //生成收购单
            OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
            orderPetAcquisition.setOrderSn( CodeGenerateUtils.generateOrderSn(dto.getHandler()));
            orderPetAcquisition.setDigest(dto.getNote());
            orderPetAcquisition.setLastConfirmTime(new Date(System.currentTimeMillis() + 3*24*60*60*1000));
            orderPetAcquisition.setState(0);
            orderPetAcquisition.setPrice(new BigDecimal(msg.getPrice()));
            orderPetAcquisition.setUserId(msg.getUserId());
            orderPetAcquisition.setShopId(employee.getShopId());
            orderPetAcquisition.setEmpId(employee.getId());
            orderPetAcquisition.setAddress(msg.getAddress());
            orderPetAcquisition.setSearchMasterMsgId(msg.getId());
            orderPetAcquisitionMapper.add(orderPetAcquisition);

            producer(orderPetAcquisition);


        }

    }

    private void producer( OrderPetAcquisition orderPetAcquisition)throws Exception  {
        // 1.创建一个默认的生产者对象，并设置生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("delay_group_name");

        // 2.设置NameServer的地址
        producer.setNamesrvAddr("localhost:9876");

        // 3.启动Producer实例
        producer.start();
        String msgJson = JSON.toJSONString(orderPetAcquisition);
        // 4.创建消息，并指定Topic，Tag和消息体  JSON
        Message msg = new Message("order-delay-topic" /* Topic */,
                "pet-delay-tag" /* Tag */,
                msgJson.getBytes(StandardCharsets.UTF_8)
        );

        // 设置延迟等级为3 10S
        msg.setDelayTimeLevel(3);

        // rocketmq的业务异步跟消息的同步有没有关系？
        // 同步消息：必须等待响应结果拿到了才能执行后续代码
        // 异步消息：不管是否拿到响应结果，继续执行下一句代码
        // 单向消息：只管发，不管消息是否成功，也就是没有响应

        // 5.发送同步消息
        SendResult send = producer.send(msg);
        System.out.println(send);
        // 7.如果不再发送消息，关闭Producer实例。
        producer.shutdown();
    }
}

